// VBConversions Note: VB project level imports
using System.Collections.Generic;
using System;
using System.Linq;
using System.Drawing;
using System.Diagnostics;
using Microsoft.VisualBasic;
using System.Xml.Linq;
using Microsoft.VisualBasic.Compatibility;
using System.Windows.Forms;
using System.Collections;
using System.Data;
// End of VB project level imports

using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop;
using System.Threading;
using System.IO;
using System.ComponentModel;


namespace 喷码数据生成工具
{
	public partial class frmTiaomaBiaoqian
	{
		string fileName;
		public struct DataItem
		{
			public string num;
			public string 站点;
		}
		public struct myData
		{
			public List<DataItem> data;
			public myData()
			{
				this.data = new List<DataItem>();
			}
		}
		List<myData> dataList = new List<myData>();
		int PageCount;
		private delegate void DLShowMessage(string msg);
		private delegate void DLShowProgress(double value, double Max, string tipString);
		private delegate void DLCreateCompleted();
		string myTitle; // VBConversions Note: Initial value cannot be assigned here since it is non-static.  Assignment has been moved to the class constructors.
		public void frmTiaomaBiaoqian_Load(object sender, EventArgs e)
		{
			CommFunction.ChangeButtonFromFrm(this);
			myTitle = this.Text;
		}
		
		public void Btn_OpenFile_Click(object sender, EventArgs e)
		{
			OpenFileDialog dialog = new OpenFileDialog();
			dialog.Title = "打开数据文件";
			dialog.Filter = "Excel文件(*.xls,*.xlsx)|*.xls;*.xlsx";
			if (dialog.ShowDialog(this) == DialogResult.OK)
			{
				TB_FileName.Text = dialog.FileName;
				TB_FileName.SelectionStart = TB_FileName.Text.Length;
				fileName = TB_FileName.Text;
			}
		}
		Thread Createth;
		bool IsCreating = false;
		public void Btn_Create_Click(object sender, EventArgs e)
		{
			try
			{
				PageCount = Convert.ToInt32(TB_Count.Text);
				setObjectEnabled(false);
				Createth = new Thread(new ThreadStart(CreateThread));
				Createth.Start();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}
		private void CreateThread()
		{
			try
			{
				IsCreating = true;
				Excel.Application app = new Excel.Application();
				Workbook wb = app.Workbooks.Open(fileName);
				int sCount = System.Convert.ToInt32(wb.Worksheets.Count);
				double lCount = 0;
				dataList = new List<myData>();
				for (var i = 1; i <= sCount; i++)
				{
					Worksheet curSheet = (Worksheet) (wb.Worksheets.Item(i));
					string zd = curSheet.Name;
					int rCount = curSheet.UsedRange.Rows.Count;
					myData curData = new myData();
					curData.data = new List<DataItem>();
					for (var j = 2; j <= rCount; j++)
					{
						DataItem tmpItem = new DataItem();
						tmpItem.站点 = zd;
						tmpItem.num = System.Convert.ToString(curSheet.Cells[j, 5].value);
						curData.data.Add(tmpItem);
						this.Invoke(new DLShowProgress(ShowProgress), j, rCount, "任务进度：" + i.ToString() + "/" + sCount.ToString());
						lCount++;
					}
					dataList.Add(curData);
				}
				string saveFileName = getSaveFileName();
				FileStream fs = new FileStream(saveFileName, FileMode.Create, FileAccess.Write);
				StreamWriter fw = new StreamWriter(fs, System.Text.Encoding.UTF8);
				double lIndex = 0;
				foreach (myData item in dataList)
				{
					int curIndex = 0;
					for (var i = 0; i <= item.data.Count - 1; i++)
					{
						try
						{
							DataItem pItem = item.data[System.Convert.ToInt32(i)];
							if (curIndex == 0)
							{
								fw.WriteLine(pItem.num);
								if (i + PageCount - 1 < item.data.Count)
								{
									fw.WriteLine(item.data[System.Convert.ToInt32(i + PageCount - 1)].num);
								}
								else
								{
									fw.WriteLine(item.data[item.data.Count - 1].num);
								}
								fw.WriteLine(pItem.站点);
							}
						}
						catch (Exception es)
						{
							writeErrorMessage(es.Message + "--" + item.data[0].站点);
						}
						curIndex++;
						if (curIndex == PageCount)
						{
							curIndex = 0;
						}
						lIndex++;
						this.Invoke(new DLShowProgress(ShowProgress), lIndex, lCount, "创建数据");
					}
				}
				fw.Close();
				fs.Close();
				wb.Close();
				app.Quit();
				IsCreating = false;
				try
				{
					this.Invoke(new DLCreateCompleted(CreateCompleted));
					System.Threading.Thread th = System.Threading.Thread.CurrentThread;
					th.Abort();
				}
				catch
				{
				}
			}
			catch (Exception ex)
			{
				IsCreating = false;
				this.Invoke(new DLShowMessage(showMessage), ex.Message);
				try
				{
					System.Threading.Thread th = System.Threading.Thread.CurrentThread;
					th.Abort();
				}
				catch
				{
				}
			}
		}
		private void writeErrorMessage(string errMsg)
		{
			FileStream fs = new FileStream(System.Reflection.Assembly.GetExecutingAssembly().Location + "\\log.txt", FileMode.Append, FileAccess.Write);
			StreamWriter fw = new StreamWriter(fs, System.Text.Encoding.UTF8);
			fw.WriteLine(DateTime.Now.ToString() + "  " + errMsg);
			fw.Close();
			fs.Close();
		}
		private void CreateCompleted()
		{
			setObjectEnabled(true);
			this.Text = myTitle;
		}
		private void ShowProgress(double value, double Max, string tipString)
		{
			try
			{
				Prog.Maximum = Max;
				Prog.Value = value;
				if (tipString != null && tipString.Length > 0 && this.Text != (myTitle + "--" + tipString))
				{
					this.Text = myTitle + "--" + tipString;
				}
			}
			catch (Exception)
			{
				// MsgBox(ex.Message)
			}
		}
		private void showMessage(string msg)
		{
			if (msg == "正在中止线程。")
			{
				return ;
			}
			Interaction.MsgBox(msg, MsgBoxStyle.OkOnly, "错误");
		}
		private string getSaveFileName()
		{
			int lIndex = fileName.LastIndexOf(".");
			if (lIndex > 0)
			{
				return fileName.Substring(0, lIndex) + ".txt";
			}
			else
			{
				return fileName + ".txt";
			}
		}
		private void setObjectEnabled(bool value)
		{
			this.Btn_Create.Enabled = value;
			this.Btn_OpenFile.Enabled = value;
			this.TB_Count.Enabled = value;
			this.TB_FileName.Enabled = value;
		}
		
		public void frmTiaomaBiaoqian_Closed(object sender, EventArgs e)
		{
			
		}
		
		public void frmTiaomaBiaoqian_Closing(object sender, CancelEventArgs e)
		{
			if (IsCreating)
			{
				if (MessageBox.Show(this, "数据生成操作未结束，是否继续退出？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
				{
					if (Createth != null)
					{
						try
						{
							Createth.Abort();
						}
						catch
						{
						}
					}
				}
				else
				{
					e.Cancel = true;
				}
			}
		}
	}
}
